/* eslint-disable no-prototype-builtins */
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import {
  getUserId,
  getToken,
  getEntSpaceId,
  getSpaceId,
  removeSpaceId,
  removeToken,
  removeUserId,
  removeEntSpaceId
} from './auth'
import msgTie from '@/utils/exception'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000  //request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (!config.data) {
      config.data = {}
    }
    if (config.data.hasOwnProperty('d')) {
      if (config.data.d.hasOwnProperty('c')) {
        if (Object.prototype.toString.call(config.data.d.c) !== '[object Array]') {
          config.data.d.c = []
        }
      } else {
        config.data.d['c'] = []
      }
      if (config.data.d.hasOwnProperty('filters')) {
        if (Object.prototype.toString.call(config.data.d.filters) !== '[object Array]') {
          config.data.d.filters = []
        }
      } else {
        config.data.d['filters'] = []
      }
      if (config.data.d.hasOwnProperty('sorts')) {
        if (Object.prototype.toString.call(config.data.d.sorts) !== '[object Array]') {
          config.data.d.sorts = []
        }
      } else {
        config.data.d['sorts'] = []
      }
      if (config.data.d.hasOwnProperty('retOnlySt')) {
        if (Object.prototype.toString.call(config.data.d.retOnlySt) !== '[object Boolean]') {
          config.data.d.retOnlySt = false
        }
      } else {
        config.data.d['retOnlySt'] = false
      }
    } else {
      config.data['d'] = { c: [], filters: [], sorts: [], retOnlySt: false }
    }
    if (getUserId()) {
      const user = config.data.d.c.find(item => item.key === 'userId')
      if (!(user && user.value)) { config.data.d.c.push({ key: 'userId', value: getUserId() }) }
    }
    if (getToken()) {
      const token = config.data.d.c.find(item => item.key === 'authToken')
      if (!(token && token.value)) { config.data.d.c.push({ key: 'authToken', value: getToken() }) }
    }
    if (getEntSpaceId()) {
      const enterprise = config.data.d.c.find(item => item.key === 'entSpaceId')
      if (!(enterprise && enterprise.value)) { config.data.d.c.push({ key: 'entSpaceId', value: getEntSpaceId() }) }
    }
    if (getSpaceId()) {
      const project = config.data.d.c.find(item => item.key === 'spaceId')
      if (!(project && project.value)) { config.data.d.c.push({ key: 'spaceId', value: getSpaceId() }) }
    }
    if (config.data.d.filters.filter(item => item.field === 'st').length === 0) {
      config.data.d.filters.push({ field: 'st', operator: 'NE', value: 9 })
    }
    if (config.data.d.sorts && config.data.d.sorts.length === 0) {
      if (config.data.d.sorts.filter(item => item.field === 'ct').length === 0) {
        config.data.d.sorts.push({ field: 'ct', isDesc: true })
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log('error', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (response.status > 300) {
      Message({
        message: response.message || '网络异常',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          removeSpaceId()
          removeToken()
          removeUserId()
          removeEntSpaceId()
          location.reload()
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      if (response.request.responseType === 'blob') {
        return response
      } else {
        return res
      }
    }
  },
  error => {
    if (error.response && error.response.status == 400) {
      msgTie(error)
    }
    return Promise.reject()
  }
)

export default service
